package com.common.www.receiver;


import com.common.www.service.TestDatabaseService;
import com.common.www.bean.entity.TestDatabase;
import com.common.www.redis.lock.LockUtil;
import com.common.www.service.redis.RedisTemplateService;
import com.common.www.utils.TxtUtil;
import com.rabbitmq.client.Channel;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@RabbitListener(queues = "com.design.www.testorder.queue")//监听的队列名称 TestDirectQueue
public class TestOrderDirectReceiver implements ChannelAwareMessageListener {
    @Autowired
    TestDatabaseService testDatabaseService;
    @Autowired
    RedisTemplateService redisTemplateService;

//    @RabbitHandler
//    public void process(HashMap hashMap) {
//        System.out.println("DirectReceiver消费者收到消息  : " + System.currentTimeMillis());

//    }

    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            //因为传递消息的时候用的map传递,所以将Map从Message内取出需要做些处理
            String msg = message.toString();
            String[] msgArray = msg.split("'");//可以点进Message里面看源码,单引号直接的数据就是我们的map消息数据
            Map<String, Object> msgMap = mapStringToMap(msgArray[1].trim());
            Object id = msgMap.get("id");
            System.out.println("DirectReceiver消费者收到消息  : " + id);
            String key = "order-" + id;

            //未抢到锁重新放回队列
            boolean lock = LockUtil.tryLock(key);
            if (!lock) {
                channel.basicReject(deliveryTag, true);//为true会重新放回队列
                return;
            }
            TestDatabase testDatabase = testDatabaseService.findOne(TxtUtil.getLong(id + ""));
            if (testDatabase.getInventory() <= 0) {
                return;
            }
            testDatabase.setInventory(testDatabase.getInventory() - 1);
            testDatabaseService.save(testDatabase);

            LockUtil.unlock(key);//释放锁
            channel.basicAck(deliveryTag, true);
//            channel.basicReject(deliveryTag, false);//拒绝不再处理
        } catch (Exception e) {
//            channel.basicReject(deliveryTag, false);//拒绝不再处理
            channel.basicReject(deliveryTag, true);//为true会重新放回队列
            e.printStackTrace();
        }
    }

    //{key=value,key=value,key=value} 格式转换成map
    private Map<String, Object> mapStringToMap(String str) {
        str = str.substring(1, str.length() - 1);
        String[] strs = str.split(",");
        Map<String, Object> map = new HashMap<String, Object>();
        for (String string : strs) {
            String key = string.split("=")[0].trim();
            String value = string.split("=")[1];
            map.put(key, value);
        }
        return map;
    }

}